library(tidyverse) # for data cleaning and plotting
library(gardenR) # for Lisa's garden data
library(lubridate) # for date manipulation
library(openintro) # for the abbr2state() function
library(palmerpenguins)# for Palmer penguin data
library(maps) # for map data
library(ggmap) # for mapping points on maps
library(gplots) # for col2hex() function
library(RColorBrewer) # for color palettes
library(sf) # for working with spatial data
library(leaflet) # for highly customizable mapping
library(ggthemes) # for more themes (including theme_map())
library(plotly) # for the ggplotly() - basic interactivity
library(gganimate) # for adding animation layers to ggplots
library(transformr) # for "tweening" (gganimate)
library(gifski) # need the library for creating gifs but don't need to load each time
library(shiny) # for creating interactive apps
library(babynames) # to use the babynames dataset
library(ggimage) # to replace a point with an image
theme_set(theme_minimal())
# SNCF Train data
small_trains <- read_csv("https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2019/2019-02-26/small_trains.csv")
# Lisa's garden data
data("garden_harvest")
# Lisa's Mallorca cycling data
mallorca_bike_day7 <- read_csv("https://www.dropbox.com/s/zc6jan4ltmjtvy0/mallorca_bike_day7.csv?dl=1") %>%
select(1:4, speed)
# Heather Lendway's Ironman 70.3 Pan Am championships Panama data
panama_swim <- read_csv("https://raw.githubusercontent.com/llendway/gps-data/master/data/panama_swim_20160131.csv")
panama_bike <- read_csv("https://raw.githubusercontent.com/llendway/gps-data/master/data/panama_bike_20160131.csv")
panama_run <- read_csv("https://raw.githubusercontent.com/llendway/gps-data/master/data/panama_run_20160131.csv")
#COVID-19 data from the New York Times
covid19 <- read_csv("https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-states.csv")
#Home Ownerhsip data from Wealth and Income over time tidytues
home_owner <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2021/2021-02-09/home_owner.csv')
#Baby names data
data("babynames")
Go here or to previous homework to remind yourself how to get set up.
Once your repository is created, you should always open your project rather than just opening an .Rmd file. You can do that by either clicking on the .Rproj file in your repository folder on your computer. Or, by going to the upper right hand corner in R Studio and clicking the arrow next to where it says Project: (None). You should see your project come up in that list if you’ve used it recently. You could also go to File –> Open Project and navigate to your .Rproj file.
Put your name at the top of the document.
For ALL graphs, you should include appropriate labels.
Feel free to change the default theme, which I currently have set to theme_minimal().
Use good coding practice. Read the short sections on good code with pipes and ggplot2. This is part of your grade!
NEW!! With animated graphs, add eval=FALSE to the code chunk that creates the animation and saves it using anim_save(). Add another code chunk to reread the gif back into the file. See the tutorial for help.
When you are finished with ALL the exercises, uncomment the options at the top so your document looks nicer. Don’t do it before then, or else you might miss some important warnings and messages.
ggplotly() function.home_owner_plot <- home_owner %>%
# mutate(mean_pct = mean(home_owner_pct)) %>%
ggplot +
geom_line((aes(x = year, y = home_owner_pct, color = race))) +
geom_hline(aes(yintercept = mean(home_owner_pct))) +
theme_tufte() +
labs(title = "Home Ownership by Race", x = "", y = "", color = "", caption = "Brett Hunsanger | Tidy Tuesday")
ggplotly(home_owner_plot)
baby_name_plot <- babynames %>%
group_by(year, sex) %>%
summarize(names_used = n()) %>%
ggplot(aes(x = year, y = names_used, color = sex)) +
geom_line() +
labs(title = "Number of Unique Names Over Time", x = "", y = "") +
theme_tufte()
ggplotly(baby_name_plot)
small_trains dataset that contains data from the SNCF (National Society of French Railways). These are Tidy Tuesday data! Read more about it here.small_trains %>%
filter(departure_station == "PARIS MONTPARNASSE") %>%
ggplot() +
geom_col(aes(x = year, y = delayed_number)) +
transition_states(delay_cause, transition_length = 0, state_length = 5) +
labs(title = "Departure Delay Causes from Paris Montparnasse",
subtitle = "Delay Cause: {closest_state}",
x = "",
y = "") +
theme(legend.position = "none")
anim_save("small_trains.gif")
knitr::include_graphics("small_trains.gif")
geom_area() examples here). You will look at cumulative harvest of tomato varieties over time. You should do the following:garden_harvest data, filter the data to the tomatoes and find the daily harvest in pounds for each variety.fct_reorder()) from most to least harvested (most on the bottom).I have started the code for you below. The complete() function creates a row for all unique date/variety combinations. If a variety is not harvested on one of the harvest dates in the dataset, it is filled with a value of 0.
garden_harvest %>%
filter(vegetable == "tomatoes") %>%
group_by(date, variety) %>%
summarize(daily_harvest_lb = sum(weight)*0.00220462) %>%
ungroup() %>%
complete(variety, date, fill = list(daily_harvest_lb = 0)) %>%
group_by(variety) %>%
mutate(cum_tomatoes = cumsum(daily_harvest_lb)) %>%
ggplot(aes(x = date, y = cum_tomatoes,
fill = fct_reorder(variety, cum_tomatoes, max))) +
geom_area() +
transition_reveal(date) +
labs(title = "Cumulative Tomato Harvest", fill = "")
anim_save("cum_tomatoes.gif")
knitr::include_graphics("cum_tomatoes.gif")
mallorca_bike_day7 bike ride using animation! Requirements:ggmap.ggimage package and geom_image to add a bike image instead of a red point. You can use this image. See here for an example.bike_image_link <- "https://raw.githubusercontent.com/llendway/animation_and_interactivity/master/bike.png"
mallorca_map <- get_stamenmap(
bbox = c(left = 2.28, bottom = 39.41, right = 2.8, top = 39.8),
maptype = "terrain",
zoom = 11
)
bikemap_anim <- mallorca_map %>%
ggmap() +
geom_path(data = mallorca_bike_day7,
aes(x = lon, y = lat, color = ele),
size = .7) +
geom_image(data = mallorca_bike_day7 %>%
mutate(image = bike_image_link),
aes(x = lon, y = lat, image = image),
size = .05) +
scale_color_viridis_c(option = "viridis") +
theme_map() +
theme(legend.background = element_blank()) +
transition_reveal(time) +
labs(title = "Follow My Mallorca Bike Trip!",
subtitle = "time: {frame_along}")
animate(bikemap_anim)
anim_save("bike_trip.gif")
knitr::include_graphics("bike_trip.gif")
I like this animated version of the graph more than the static plot. It reveals the direction of travel and also shows the pause in the ride about 3/4 of the way through. It feels more personable especially if you are trying to share your trip with others.
panama_swim, panama_bike, and panama_run. Create a similar map to the one you created with my cycling data. You will need to make some small changes: 1. combine the files (HINT: bind_rows(), 2. make the leading dot a different color depending on the event (for an extra challenge, make it a different image using `geom_image()!), 3. CHALLENGE (optional): color by speed, which you will need to compute on your own from the data. You can read Heather’s race report here. She is also in the Macalester Athletics Hall of Fame and still has records at the pool.panama_map <- get_stamenmap(
bbox = c(left = -79.58, bottom = 8.90, right = -79.4489, top = 8.9912),
maptype = "terrain",
zoom = 13)
panama_tri <- bind_rows(panama_swim, panama_bike, panama_run)
tri_anim <- ggmap(panama_map) +
geom_path(data = panama_tri,
aes(x = lon, y = lat, color = ele),
size = .7) +
geom_point(data = panama_tri,
aes(x = lon, y = lat),
size = .7) +
scale_color_viridis_c(option = "viridis") +
theme_map() +
theme(legend.background = element_blank()) +
transition_reveal(time) +
labs(title = "Panama Triathlon",
subtitle = "Heather Lendway Ironman 70.3 Pan AM Championships",
caption = "time: {frame_along}")
animate(tri_anim)
anim_save("panama_tri.gif")
knitr::include_graphics("panama_tri.gif")
Not sure why, but I could not get the geom_point to color by event :(
lag() function you’ve used in a previous set of exercises). Replace missing values with 0’s using replace_na().geom_path() and add a group aesthetic. Put the x and y axis on the log scale and make the tick labels look nice - scales::comma is one option. This plot will look pretty ugly as is.geom_point()) and add the state name as a label (geom_text() - you should look at the check_overlap argument).animate() function to have 200 frames in your animation and make it 30 seconds long.covid_anim <- covid19 %>%
group_by(state) %>%
mutate(seven_day = lag(cases, 7, order_by = date)) %>%
replace_na(list(seven_day = 0)) %>%
mutate(weekly_cases = (cases - seven_day)/ 7) %>%
filter(seven_day > 20) %>%
ggplot(aes(x = cases, y = weekly_cases, group = state)) +
geom_point(color = "red") +
geom_path(color = "black") +
geom_text(aes(label = state, check_overlap = TRUE)) +
scale_x_log10(label = scales::comma) +
scale_y_log10(label = scales::comma) +
transition_reveal(date) +
labs(title = "Weekly Covid Case Trends in the U.S. Compared to Total cases", x = "Total Cases", y = "New Cases (weekly)", subtitle = "log scale")
animate(covid_anim, nframes = 200, duration = 30)
anim_save("covid_trends.gif")
knitr::include_graphics("covid_trends.gif")
It is nice to see new cases weekly start to fall at the very end. States tend to have the same exponential trajectory which is shown linearly because of the log scale.
states_map data. Here is a list of details you should include in the plot:wday() to create a day of week variable and filter to all the Fridays.animate() function to make the animation 200 frames instead of the default 100 and to pause for 10 frames on the end frame.group = date in aes().census_pop_est_2018 <- read_csv("https://www.dropbox.com/s/6txwv3b4ng7pepe/us_census_2018_state_pop_est.csv?dl=1") %>%
separate(state, into = c("dot","state"), extra = "merge") %>%
select(-dot) %>%
mutate(state = str_to_lower(state))
cases_with_2018_pop_est <-
covid19 %>%
mutate(state_name = str_to_lower(state)) %>%
group_by(state) %>%
left_join(census_pop_est_2018,
by = c("state_name" = "state")) %>%
mutate(cases_per_10000 = (cumsum(cases)/est_pop_2018)*10000) %>%
mutate(day_of_week = wday(date, label = TRUE)) %>%
filter(day_of_week == "Fri")
states_map <- map_data("state")
covid_anim2 <- cases_with_2018_pop_est %>%
ggplot() +
geom_map(map = states_map,
aes(map_id = state_name,
fill = cases_per_10000,
group = date)) +
scale_fill_viridis_c(option = "inferno") +
expand_limits(x = states_map$long, y = states_map$lat) +
theme_map() +
transition_time(date) +
labs(title = "Covid Cases per 10,000",
subtitle = "Date: {frame_time}")
animate(covid_anim2, nframes = 200, end_pause = 50)
anim_save("covid_anim_states.gif")
knitr::include_graphics("covid_anim_states.gif")
Pausing for 50 frames at the end seemed to be more effective at seeing the end graph. I am a bit surprised by the northeasternmost and northwesternmost states for having such low case counts comparatively. Also cases per 10.000 really escalated quickly after December.
shiny app (for next week!)NOT DUE THIS WEEK! If any of you want to work ahead, this will be on next week’s exercises.
app.R file you create. Below, you will post a link to the app that you publish on shinyapps.io. You will create an app to compare states’ cumulative number of COVID cases over time. The x-axis will be number of days since 20+ cases and the y-axis will be cumulative cases on the log scale (scale_y_log10()). We use number of days since 20+ cases on the x-axis so we can make better comparisons of the curve trajectories. You will have an input box where the user can choose which states to compare (selectInput()) and have a submit button to click once the user has chosen all states they’re interested in comparing. The graph should display a different line for each state, with labels either on the graph or in a legend. Color can be used if needed.DID YOU REMEMBER TO UNCOMMENT THE OPTIONS AT THE TOP?